package org.shilong.UI.friend;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;
import org.shilong.ActionItem;
import org.shilong.QuickAction;
import org.shilong.Loader.ImageLoader;
import org.shilong.Model.FriendModel;
import org.shilong.UI.R;
import org.shilong.Utility.IntentUtility;
import org.shilong.Utility.ProgressDialogUtility;
import org.shilong.Utility.SharedPreferenceUtility;
import org.shilong.Utility.Loader.FriendListViewLoader;
import org.shilong.Utility.Loader.NewFriendListViewLoader;
import org.shilong.Utility.constants.APIConstants;
import org.shilong.Utility.constants.WeiboConstants;

import android.app.ActivityGroup;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.weibo.net.Oauth2AccessTokenHeader;
import com.weibo.net.Utility;
import com.weibo.net.Weibo;
import com.weibo.net.WeiboException;
import com.weibo.net.WeiboParameters;

/**
 * 朋友中心的布局
 * 
 * @author cesc
 * 
 */
public class FriendCenterFrame extends ActivityGroup implements OnClickListener {

	public static List<FriendModel> friendList = new ArrayList<FriendModel>();

	private ListView friend_list_listview;

	//private TextView queryweiborelations_textview;

	private String[] arr;
	
	private ProgressDialog dialog;
	
	private List<FriendModel> friList = new ArrayList<FriendModel>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setContentView(R.layout.layout_friend_center_content);

		arr = SharedPreferenceUtility.getPersonInfoFromSharedPreference(this);
		
		initViews();
		
	}

	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	
		
	}


	private void initViews() {
		
		dialog = new ProgressDialog( FriendCenterFrame.this );
		dialog.setMessage( "获取互粉列表中.." );
		
		
		/*queryweiborelations_textview = (TextView) this
				.findViewById(R.id.queryweiborelations_textview);*/

		friend_list_listview = (ListView) this
				.findViewById(R.id.friend_list_listview);

		friend_list_listview.setFocusable(true);
		
		NewFriendListViewLoader loader = new NewFriendListViewLoader( friend_list_listview, this, null);
		
		loader.startLoader();

	}


	/**
	 * 获取好友信息列表的列表
	 * 
	 * @param rlt
	 * @return
	 */
	private List<FriendModel> getFriendList(String rlt) {

		List<FriendModel> friList = new ArrayList<FriendModel>();

		try {
			JSONObject obj = new JSONObject(rlt);

			String IDARR = obj.getString("ids");

			IDARR = IDARR.replace("[", "");
			IDARR = IDARR.replace("]", "");

			String[] arr = IDARR.split(",");

			for (String string : arr) {

				Weibo mWeibo = Weibo.getInstance();

				WeiboParameters params = new WeiboParameters();
				params.add("uid", string);

				Utility.setAuthorization(new Oauth2AccessTokenHeader());

				String re = mWeibo.request(FriendCenterFrame.this,
						"https://api.weibo.com/2/users/show.json", params,
						Utility.HTTPMETHOD_GET, mWeibo.getAccessToken());

				JSONObject oo = new JSONObject(re);

				FriendModel model = new FriendModel();

				model.setWeibo_id(oo.getString("id"));
				model.setScreen_name(oo.getString("screen_name"));
				model.setProfile_image_url(oo.getString("profile_image_url"));
				model.setLocation(oo.getString("location"));
				model.setDescription(oo.getString("description"));

				friList.add(model);
			}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (WeiboException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return friList;

	}

	private class MyAdapter extends BaseAdapter {

		private List<FriendModel> mList;

		public MyAdapter(List<FriendModel> mList) {

			this.mList = mList;

		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mList.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return mList.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			// TODO Auto-generated method stub

			final FriendModel model = mList.get(arg0);

			/*
			 * model.setWeibo_id( oo.getString("id")); model.setScreen_name(
			 * oo.getString("screen_name")); model.setProfile_image_url(
			 * oo.getString("profile_image_url")); model.setLocation(
			 * oo.getString( "location" ) ); model.setDescription( oo.getString(
			 * "description" ));
			 */

			LayoutInflater inflater = (LayoutInflater) FriendCenterFrame.this
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

			View root = inflater.inflate(
					R.layout.inner_friend_listview_item_layout, null);

			/**
			 * 初始化头像
			 */
			final ImageView iv = (ImageView) root
					.findViewById(R.id.inner_show_header_img_imageview);

			ImageLoader loader = new ImageLoader();

			Drawable draw = loader.loadImage(model.getProfile_image_url()
					+ ".jpg", new ImageLoader.ImageCallBack() {

				@Override
				public void setImageDrawable(Drawable imageDrawable) {
					// TODO Auto-generated method stub

					iv.setImageDrawable(imageDrawable);
				}
			});

			if (draw != null)
				iv.setImageDrawable(draw);

			TextView inner_friend_screen_name_textview = (TextView) root
					.findViewById(R.id.inner_friend_screen_name_textview);
			TextView inner_friend_location_textview = (TextView) root
					.findViewById(R.id.inner_friend_location_textview);
			TextView inner_friend_desc_textview = (TextView) root
					.findViewById(R.id.inner_friend_desc_textview);

			inner_friend_screen_name_textview.setText(model.getScreen_name());
			inner_friend_location_textview.setText(model.getLocation());
			inner_friend_desc_textview.setText(model.getDescription());

			/* 点击item时间 */

			root.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub

					Bundle bun = new Bundle();

					bun.putString("image_url", model.getProfile_image_url());
					bun.putString("weibo_id", model.getWeibo_id());

					IntentUtility.goNextFrame(FriendCenterFrame.this,
							ShowFriendDetailFrame.class, bun);

				}
			});

			return root;

		}
	}

	private class MyTask extends AsyncTask<String, String, String> {
		
		
		public MyTask() {
			// TODO Auto-generated constructor stub
			
		
		}
		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub

			// 在loginframe中封装的
			Utility.setAuthorization(new Oauth2AccessTokenHeader());

			/**
			 * 获取好友的id 列表 获取好友的具体信息
			 * 
			 */
			WeiboParameters pas = new WeiboParameters();

			pas.add("source", WeiboConstants.APIKEY);
			pas.add("uid", arr[3] );// 加着试一试 为什么我不加上也好使呢 ？

			Utility.setAuthorization(new Oauth2AccessTokenHeader()); // 加上之后就不报出现过期的等异常了

			// 获取互粉好友
			try {
				String friendsRlt = Weibo.getInstance().request(
						FriendCenterFrame.this, APIConstants.GET_FRIEND, pas,
						Utility.HTTPMETHOD_GET,
						Weibo.getInstance().getAccessToken());

				friList = getFriendList(friendsRlt);

				

			} catch (WeiboException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub

			super.onPostExecute(result);
			
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			
		}

	}

	/**
	 * 启动快速链接 查询名片
	 * 
	 * @param v
	 */
	private void quickActionMenu(View v, final FriendModel model) {

		ActionItem openAction = new ActionItem();
		openAction.setTitle("名片");
		openAction.setIcon(getResources().getDrawable(R.drawable.pl_img));

		final QuickAction mQuickAction = new QuickAction(this);
		mQuickAction.addActionItem(openAction);
		mQuickAction
				.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
					@Override
					public void onItemClick(int pos) {
						switch (pos) {
						case 0:

							businessCardLogic(model);

							break;
						case 1:

							// takePartInLogic(model);

							break;
						}
					}
				});
		mQuickAction.show(v);
	}

	private PopupWindow myPopWindow;

	private void businessCardLogic(FriendModel model) {

		myPopWindow = null;

		myPopWindow = new PopupWindow(this);

		myPopWindow.setFocusable(true);
		myPopWindow.setOutsideTouchable(true);
		myPopWindow.setTouchable(true);

		/*
		 * centerX = layout_manager_paries_father_outter_layout.getWidth() / 2;
		 * 
		 * centerY = layout_manager_paries_father_outter_layout.getHeight() / 2;
		 * 
		 * System.out.println("centerX:" + centerX);
		 * System.out.println("centerY:" + centerY);
		 * 
		 * LayoutInflater inlater = this.getLayoutInflater();
		 * 
		 * View root = inlater .inflate(R.layout.layout_comment_party_content,
		 * null);
		 * 
		 * myPopWindow.setBackgroundDrawable(getResources().getDrawable(
		 * R.drawable.special_layout_background));
		 * 
		 * myPopWindow.setWidth(layout_manager_paries_father_outter_layout
		 * .getWidth() - 20);
		 * myPopWindow.setHeight(layout_manager_paries_father_outter_layout
		 * .getHeight() - 20);
		 * 
		 * myPopWindow.setAnimationStyle(R.style.MyPopWindow);
		 * 
		 * myPopWindow.setContentView(root);
		 * 
		 * myPopWindow.showAtLocation(layout_manager_paries_father_outter_layout,
		 * Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
		 * 
		 * initCommentPopupWindowComponents(root, model);
		 */

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
	/*	switch (v.getId()) {
		case R.id.queryweiborelations_textview:

			queryRelationsLogic();

			break;

		default:
			break;
		}*/

	}

	/**
	 * 查询关系逻辑
	 */
	private void queryRelationsLogic() {

		myPopWindow = null;

		myPopWindow = new PopupWindow(this);

		myPopWindow.setFocusable(true);
		myPopWindow.setOutsideTouchable(true);
		myPopWindow.setTouchable(true);

	}
}
